﻿Imports System.Text.RegularExpressions
Imports System.Text

Public Class NuevoCliente
    Dim dsCaser As caserDataSet
    Private Sub DateTimePicker1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpFechaNac.ValueChanged

    End Sub
    Private Sub Label9_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label9.Click

    End Sub

    Private Sub Label11_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label11.Click

    End Sub

    Private Sub Label16_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub


    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Dim formPersonas As frmPersonas
        Dim duplicado As Boolean = False
        formPersonas = New frmPersonas
        formPersonas.parentesco(True)
        formPersonas.ShowDialog()
        If (formPersonas.Tag <> Nothing) Then
            Dim cadena As String
            cadena = formPersonas.Tag.ToString()
            For Each fila As DataGridViewRow In dgFamiliares.Rows
                If (fila.Cells(0).Value.Equals(cadena.Split(";")(0))) Then
                    MessageBox.Show("Familiar ya introducido por favor seleccione otro.")
                    duplicado = True
                    Exit For
                End If
            Next
            If (Not duplicado) Then
                dgFamiliares.Rows.Add()
                dgFamiliares.Rows(dgFamiliares.RowCount - 1).Cells(0).Value = cadena.Split(";")(0)
                dgFamiliares.Rows(dgFamiliares.RowCount - 1).Cells(1).Value = cadena.Split(";")(1)
                dgFamiliares.Rows(dgFamiliares.RowCount - 1).Cells(2).Value = cadena.Split(";")(2)
                dgFamiliares.Rows(dgFamiliares.RowCount - 1).Cells(3).Value = cadena.Split(";")(3)
                dgFamiliares.Rows(dgFamiliares.RowCount - 1).Cells(4).Value = cadena.Split(";")(4)
            End If

        End If




    End Sub


    Private Sub gbDatosPers_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gbDatosPers.Enter

    End Sub

    Private Sub btnDel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDel.Click
        If MessageBox.Show("¿Estas seguro que desea borrar el familiar seleccionado?.", "Eliminar", MessageBoxButtons.OKCancel) = Windows.Forms.DialogResult.OK Then
            dgFamiliares.Rows.Remove(dgFamiliares.CurrentRow)

        End If
    End Sub

    Public Sub nuevoCliente(ByVal visible As Boolean)
        gbFamiliares.Visible = visible
        If (Not visible) Then
            Me.Height = Me.Height - (gbFamiliares.Height)
            btnCrearCliente.Location = New Point(btnCrearCliente.Location.X, btnCrearCliente.Location.Y - (gbFamiliares.Height))
            btnCancelar.Location = New Point(btnCancelar.Location.X, btnCancelar.Location.Y - (gbFamiliares.Height))
        End If



    End Sub

    Private Sub NuevoCliente_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        dsCaser = New caserDataSet
        cmbTrabajo.SelectedIndex = 0

    End Sub

    Private Sub btnCrearCliente_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCrearCliente.Click

        If (validar()) Then
            dsCaser.personas.AddpersonasRow(txtNombre.Text, txtApellidos.Text, txtDni.Text, dtpFechaNac.Value.ToShortDateString, IIf(txtTlfn1.Text = "", Nothing, txtTlfn1.Text), dtpFechaCarnet.Value.ToShortDateString, txtDireccion.Text, txtEmail.Text, cmbTrabajo.SelectedItem, nudRenta.Value, txtTipoVivienda.Text, nudNumHijos.Value, IIf(txtTlfn2.Text = "", Nothing, txtTlfn2.Text), txtLocalidad.Text)
            Dim sError As String = ""

            sError = GuardarTabla(dsCaser.personas)

            If sError <> "" Then
                MessageBox.Show(sError, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

            Dim sError2 As String = ""

            sError2 = CargarTabla(dsCaser.personas)

            Dim sError1 As String = ""
            If sError2 <> "" Then
                MessageBox.Show(sError, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Else

                Dim idPersona1 As Integer
                idPersona1 = CType(dsCaser.personas.Select("id = " & SQL_MaxCodPersona() & "")(0), Seguros.caserDataSet.personasRow).Id
                For Each row As DataGridViewRow In dgFamiliares.Rows
                    dsCaser.relaciones.AddrelacionesRow(idPersona1, row.Cells(0).Value, row.Cells(4).Value)

                Next


                sError = GuardarTabla(dsCaser.relaciones)

                If sError1 <> "" Then
                    MessageBox.Show(sError, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)

                End If

                For Each cuenta As String In lstCuentasCorientes.Items
                    dsCaser.cuentacorriente.AddcuentacorrienteRow(idPersona1, cuenta)
                Next

                sError = GuardarTabla(dsCaser.cuentacorriente)

                If sError1 <> "" Then
                    MessageBox.Show(sError, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)

                End If

            End If

            



            If sError = "" And sError1 = "" And sError2 = "" Then
                If Me.MdiParent IsNot Nothing Then
                    CType(Me.MdiParent, Principal).Estado = "Cliente resgistrado.. "
                End If
                Limpiar()

            End If
        End If
    End Sub

    Private Function validar() As Boolean
        Dim valido = True
        Dim sError = ""
        If txtNombre.Text = "" Then
            valido = False
            sError = "El campo nombre no puede ser vacio" & vbCrLf
        End If
        If txtEmail.Text <> String.Empty Then
            Dim re As Regex = New Regex("^[\w._%-]+@[\w.-]+\.[a-zA-Z]{2,4}$")
            Dim m As Match = re.Match(txtEmail.Text)
            If m.Captures.Count = 0 Then
                valido = False
                sError = "No es un email valido" & vbCrLf
            End If
        End If
        If (txtDni.Text <> "" AndAlso Not (Verificar_CIF(txtDni.Text) Or Verificar_NIF(txtDni.Text))) Then
            valido = False
            sError += " El cif o el dni no es valido" & vbCrLf
        End If


        If sError <> "" Then
            MessageBox.Show(sError, "Datos Incorrectos", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If
        ' Compruebo si el formato de la dirección es correcto.
        Return valido
    End Function

    Private Function validarCuenta() As Boolean
        Dim valido = True
        Dim sError = ""
        If txtCuenta.Text = "" Then
            valido = False
            sError = "El introduzca número de cuenta" & vbCrLf
        End If

        If sError <> "" Then
            MessageBox.Show(sError, "Datos Incorrectos", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If
        Return valido
    End Function

    Private Sub Limpiar()
        txtApellidos.Text = ""
        txtDireccion.Text = ""
        txtDni.Text = ""
        txtEmail.Text = ""
        txtLocalidad.Text = ""
        txtNombre.Text = ""
        txtTipoVivienda.Text = ""
        txtTlfn1.Text = ""
        txtTlfn2.Text = ""
        dtpFechaCarnet.Value = Date.Now
        dtpFechaNac.Value = Date.Now
        nudNumHijos.Value = 0
        nudRenta.Value = 0
        dgFamiliares.Rows.Clear()

    End Sub
    Public Function Verificar_CIF(ByVal valor As String) As Boolean
        Dim strLetra As String, strNumero As String, strDigit As String
        Dim strDigitAux As String
        Dim auxNum As Integer
        Dim i As Integer
        Dim suma As Integer
        Dim letras As String

        letras = "ABCDEFGHKLMPQSX"

        valor = UCase(valor)

        If Len(valor) < 9 OrElse Not IsNumeric(Mid(valor, 2, 7)) Then
            Return False
        End If

        strLetra = Mid(valor, 1, 1)     ' letra del CIF
        strNumero = Mid(valor, 2, 7)    ' Codigo de Control
        strDigit = Mid(valor, 9)        ' CIF menos primera y ultima posiciones

        If InStr(letras, strLetra) = 0 Then ' comprobamos la letra del CIF (1ª posicion)
            Return False
        End If

        For i = 1 To 7
            If i Mod 2 = 0 Then
                suma = suma + CInt(Mid(strNumero, i, 1))
            Else
                auxNum = CInt(Mid(strNumero, i, 1)) * 2
                suma = suma + (auxNum \ 10) + (auxNum Mod 10)
            End If
        Next

        suma = (10 - (suma Mod 10)) Mod 10

        Select Case strLetra
            Case "K", "P", "Q", "S"
                suma = suma + 64
                strDigitAux = Chr(suma)
            Case "X"
                strDigitAux = Mid(CalculaNIF(strNumero), 8, 1)
            Case Else
                strDigitAux = CStr(suma)
        End Select

        If strDigit = strDigitAux Then
            Return True
        Else
            Return False
        End If
    End Function
    Public Function Verificar_NIF(ByVal valor As String) As Boolean
        Dim aux As String

        valor = valor.ToUpper ' ponemos la letra en mayúscula
        aux = valor.Substring(0, valor.Length - 1) ' quitamos la letra del NIF

        If aux.Length >= 7 AndAlso IsNumeric(aux) Then
            aux = CalculaNIF(aux) ' calculamos la letra del NIF para comparar con la que tenemos
        Else
            Return False
        End If

        If valor <> aux Then ' comparamos las letras
            Return False
        End If

        Return True
    End Function

    Private Function CalculaNIF(ByVal strA As String) As String
        '----------------------------------------------------------------------
        ' Calcular la letra del NIF
        ' Código original adaptado a Visual Basic                   (13/Sep/95)
        ' Adaptado a Visual Basic .NET (VB 9.0/2008)                (09/May/08)
        ' y convertido en función que devuelve el NIF correcto
        '----------------------------------------------------------------------
        Const cCADENA As String = "TRWAGMYFPDXBNJZSQVHLCKE"
        Const cNUMEROS As String = "0123456789"
        Dim a, b, c, NIF As Integer
        Dim sb As New StringBuilder

        strA = Trim(strA)
        If Len(strA) = 0 Then Return ""

        ' Dejar sólo los números
        For i As Integer = 0 To strA.Length - 1
            If cNUMEROS.IndexOf(strA(i)) > -1 Then
                sb.Append(strA(i))
            End If
        Next

        strA = sb.ToString
        a = 0
        NIF = CInt(Val(strA))
        Do
            b = CInt(Int(NIF / 24))
            c = NIF - (24 * b)
            a = a + c
            NIF = b
        Loop While b <> 0
        b = CInt(Int(a / 23))
        c = a - (23 * b)

        Return strA & Mid(cCADENA, CInt(c + 1), 1)
    End Function

    Private Sub btnCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelar.Click
        Me.Close()

    End Sub

    Private Sub btnAñadirCuenta_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAñadirCuenta.Click
        If validarCuenta() Then
            lstCuentasCorientes.Items.Add(txtCuenta.Text)
            txtCuenta.Clear()
        End If
    End Sub

    Private Sub btnEliminarCuenta_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEliminarCuenta.Click
        If lstCuentasCorientes.SelectedItem IsNot Nothing Then
            lstCuentasCorientes.Items.Remove(lstCuentasCorientes.SelectedItem)
        End If
    End Sub
End Class